package com.jht.bletool.fragment;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.permissions.OnPermission;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;
import com.jht.bletool.APP;
import com.jht.bletool.R;
import com.jht.bletool.adapter.BleDeviceAdapter;
import com.jht.bletool.config.AppConfig;
import com.jht.bletool.config.AppConfigFactory;
import com.jht.bletool.entity.BleDevice;
import com.jht.bletool.ui.DataTransmissionActivity;
import com.jht.bletool.ui.UIKeyCode;
import com.jht.bletool.util.BaseUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.List;

import it.gmariotti.recyclerview.adapter.SlideInBottomAnimatorAdapter;

import static android.app.Activity.RESULT_OK;
import static android.bluetooth.BluetoothAdapter.STATE_OFF;
import static android.bluetooth.BluetoothAdapter.STATE_TURNING_OFF;
import static android.bluetooth.BluetoothAdapter.STATE_TURNING_ON;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BleDevicesFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BleDevicesFragment extends Fragment implements BleDeviceAdapter.StopScanCallback {
    private static final String TAG = "BleDevicesFragment";
    public static String ACTION_REFRESH = "com.jht.ble.rescan";
    public final int REQUEST_ENABLE_BT = 10;
    private Context mContext;
    private Handler uiHandler;
    private SmartRefreshLayout mRefreshLayout;
    private RecyclerView mLvBleDevices;
    private LinearLayout mLlEmptyView;
    private BluetoothAdapter bluetoothAdapter;
    private BleDeviceAdapter bleDeviceAdapter;
    private boolean isNUll = true;
    private BtAndGpsReceiver btAndGpsReceiver;
    private AppConfig appConfig = AppConfigFactory.getAppConfigInstance();


    private int Scan_state = UIKeyCode.SCAN_STATE_INIT;

    private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
        private volatile boolean isFirst = true;
        private Object lock = new Object();

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, final byte[] scanRecord) {
            String hexString = AppConfig.getHexString(scanRecord);
            Log.i(TAG, "onLeScan: 扫描的回调是在主线程中的！1");
            if (Scan_state != UIKeyCode.SCAN_STATE_START) {
                return;
            }

            if ("".equals(device.getName()) || device.getName() == null) {
                return;
            }

            bleDeviceAdapter.addDevice(new BleDevice(device, rssi, scanRecord));
        }
    };

    private Runnable stopScan = new Runnable() {
        @Override
        public void run() {
            uiHandler.sendEmptyMessage(UIKeyCode.UI_STOP_ROTATION);
            bluetoothAdapter.stopLeScan(leScanCallback);
        }
    };

    public BleDevicesFragment(Context context, Handler uiHandler) {
        this.mContext = context;
        this.uiHandler = uiHandler;
    }

    public static BleDevicesFragment newInstance(Context context, Handler uiHandler) {
        BleDevicesFragment fragment = new BleDevicesFragment(context, uiHandler);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final BluetoothManager bluetoothManager =
                (BluetoothManager) (APP.getAppContext().getSystemService(Context.BLUETOOTH_SERVICE));
        bluetoothAdapter = bluetoothManager.getAdapter();
        Log.i(TAG, "onCreate: " + bluetoothAdapter);

        btAndGpsReceiver = new BtAndGpsReceiver();
        getActivity().registerReceiver(btAndGpsReceiver, getFilters());

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_refresh_ble_devices, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRefreshLayout = view.findViewById(R.id.refresh_layout);
        mRefreshLayout.setEnableLoadMore(false);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                requestPermissions();
                mRefreshLayout.finishRefresh(1000);
            }
        });
        mLlEmptyView = view.findViewById(R.id.ll_empty_device_view);
        mLvBleDevices = view.findViewById(R.id.lv_ble_devices);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        mLvBleDevices.setLayoutManager(linearLayoutManager);
        bleDeviceAdapter = new BleDeviceAdapter(getActivity());
        bleDeviceAdapter.setStopScanCallback(this);
        SlideInBottomAnimatorAdapter<BleDeviceAdapter.BleDeviceViewHolder> animatorAdapter = new SlideInBottomAnimatorAdapter<BleDeviceAdapter.BleDeviceViewHolder>(bleDeviceAdapter, mLvBleDevices);
        mLvBleDevices.setAdapter(bleDeviceAdapter);


    }

    private void requestPermissions() {
        XXPermissions.with(getActivity())
                // 可设置被拒绝后继续申请，直到用户授权或者永久拒绝
                .constantRequest()
                // 支持请求6.0悬浮窗权限8.0请求安装权限
                //.permission(Permission.SYSTEM_ALERT_WINDOW, Permission.REQUEST_INSTALL_PACKAGES)
                // 不指定权限则自动获取清单中的危险权限
                // .permission(Permission.Group.STORAGE, Permission.Group.CALENDAR)
                .request(new OnPermission() {

                    @Override
                    public void hasPermission(List<String> granted, boolean all) {
                        if (!all) {
                            uiHandler.sendEmptyMessage(UIKeyCode.UI_SHOW_GO_SETTING_DIALOG);
                        } else {
                            // 权限全部授予，可以开始扫描ble设备
                            if (isBTOpen(bluetoothAdapter) && isGPSOpen()) {
                                //开始扫描
                                Log.i(TAG, "hasPermission: isGPSOpen() ==> " + isGPSOpen());
                                Scan_state = UIKeyCode.SCAN_STATE_START;
                                bleDeviceAdapter.clear();
                                bluetoothAdapter.startLeScan(leScanCallback);
                                uiHandler.postDelayed(stopScan, appConfig.getScanTime());
                                uiHandler.sendEmptyMessage(UIKeyCode.UI_START_ROTATION);
                            } else {

                                switch (bluetoothAdapter.getState()) {
                                    case STATE_OFF:
                                    case STATE_TURNING_OFF:
                                        ToastUtils.show(R.string.open_bt_gps);
                                        return;
                                    case STATE_TURNING_ON:
                                        ToastUtils.show(R.string.bt_turning_on);
                                        return;
                                    default:
                                        Log.w(TAG, "hasPermission: 蓝牙状态："+ bluetoothAdapter.getState() );
                                }
                                if (!isGPSOpen()) {
                                    ToastUtils.show(R.string.gps_not_open);
                                }

                            }
                        }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        Log.i(TAG, "noPermission: " + denied + " ; " + quick);
                    }
                });
    }

    private void showTestData() {
        bleDeviceAdapter.clear();
    }

    private void openBT() {
        if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    }

    private boolean isBTOpen(BluetoothAdapter btAdapter) {
        if (btAdapter == null || !btAdapter.isEnabled()) {
            if (btAdapter == null){
                final BluetoothManager bluetoothManager =
                        (BluetoothManager) (APP.getAppContext().getSystemService(Context.BLUETOOTH_SERVICE));
                bluetoothAdapter = bluetoothManager.getAdapter();
            }
            return false;
        }
        return true;
    }

    private boolean isGPSOpen() {
        LocationManager locationManager = (LocationManager) (APP.getAppContext()).getSystemService(Context.LOCATION_SERVICE);
        boolean gpsLocation = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean networkLocation = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gpsLocation || networkLocation) {
            return true;
        }
        return false;
    }

    private IntentFilter getFilters() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION);
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        filter.addAction(ACTION_REFRESH);
        return filter;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == this.REQUEST_ENABLE_BT) {
            if (resultCode == RESULT_OK) {
                Log.i(TAG, "onActivityResult: ok");
            } else {
                Log.i(TAG, "onActivityResult: resultCode ==> " + resultCode);
            }
        }

    }

    @Override
    public void onStop() {
        super.onStop();
        Log.e(TAG, "onStop: 主动停止ble扫描");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(btAndGpsReceiver);
    }
    private boolean canClick = true;
    @Override
    public void stopScan(BluetoothDevice device, String machineType) {
        if (canClick){
            Log.e(TAG, "stopScan: 主动停止ble扫描");
            //停止蓝牙扫描

            uiHandler.post(stopScan);
            Intent intent = new Intent();
            intent.setClass(APP.getAppContext(), DataTransmissionActivity.class);
            intent.putExtra("ble_device",device);
            intent.putExtra("scan_record",machineType);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            APP.getAppContext().startActivity(intent);

        }

    }

    private class BtAndGpsReceiver extends BroadcastReceiver {
        /**
         * int STATE_OFF = 10; //bt closed
         * int STATE_ON = 12; //bt opened
         * int STATE_TURNING_OFF = 13; //bt is closing
         * int STATE_TURNING_ON = 11; //bt is opening
         *
         * @param context
         * @param intent
         */
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.i(TAG, "onReceive == action " + action);
            if (LocationManager.PROVIDERS_CHANGED_ACTION.equals(action) || BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                if (!isBTOpen(bluetoothAdapter) || !isGPSOpen()) {
                    Log.i(TAG, "onReceive: isBTOpen(bluetoothAdapter)");
                    bluetoothAdapter.stopLeScan(leScanCallback);
                    Scan_state = UIKeyCode.SCAN_STATE_STOP;
                    bleDeviceAdapter.clear();
                    uiHandler.sendEmptyMessage(UIKeyCode.UI_STOP_ROTATION);
                }
            } else if (ACTION_REFRESH.equals(action)) {

            }

        }

    }

}